package com.transaction.demo.notify.mq;

import java.lang.reflect.Type;
import java.util.Map;

import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

import com.google.gson.reflect.TypeToken;
import com.transaction.demo.common.util.JsonUtils;
import com.transaction.demo.common.util.Result;
import com.transaction.demo.common.util.StringUtil;
import com.transaction.demo.message.MessageService;
import com.transaction.demo.message.vo.req.TransactionMessageAddReqVo;
import com.transaction.demo.notify.config.NotifyConfig;
import com.transaction.demo.notify.enums.NotifyStatusEnum;
import com.transaction.demo.notify.service.NotifyRecordService;
import com.transaction.demo.notify.vo.req.NotifyRecordAddReqVo;
import com.transaction.demo.notify.vo.req.NotifyRecordReqVo;
import com.transaction.demo.notify.vo.resp.NotifyRecordRespVo;

@Slf4j
@Service
@RocketMQMessageListener(consumerGroup = "merchant_notify", topic = "MERCHANT_NOTIFY")
public class NotifyMessageListener implements RocketMQListener<String> {

	@Autowired
	private NotifyRecordService notifyRecordService;

	@Autowired
	private MessageService messageService;

	@Autowired
	private NotifyConfig config;

	@Override
	public void onMessage(String s) {
		log.info("通知服务接收到银行回调消息：{}", s);

		Type type = new TypeToken<Map<String, String>>() {
		}.getType();

		Map<String, String> params = JsonUtils.fromJson(s, type);

		if (params == null) {
			return;
		}

		String id = params.get("id");
		String businessId = params.get("businessId");

		if (!StringUtil.isEmpty(id)) {
			NotifyRecordRespVo notifyRecord = notifyRecordService.queryNotifyRecord(
					NotifyRecordReqVo.builder().id(id).build());
			if (notifyRecord != null) {
				return;
			}
		}

		NotifyRecordAddReqVo reqVo = new NotifyRecordAddReqVo();
		reqVo.setId(StringUtil.get32UUID());
		reqVo.setVersion(0);
		reqVo.setNotifyRule("");
		reqVo.setNotifyTimes(0);
		reqVo.setLimitNotifyTimes(config.maxSendTimes);
		reqVo.setUrl(config.notifyUrl);
		reqVo.setMerchantOrderNo(businessId);
		reqVo.setMerchantNo(businessId);
		reqVo.setStatus(NotifyStatusEnum.CREATED.name());
		reqVo.setNotifyType("http");

		NotifyRecordRespVo recordRespVo = notifyRecordService.saveNotifyRecord(reqVo);

		TransactionMessageAddReqVo messageAddReqVo = new TransactionMessageAddReqVo();
		messageAddReqVo.setMessageId(StringUtil.get32UUID());
		messageAddReqVo.setMessageBody(JsonUtils.toJson(recordRespVo));
		messageAddReqVo.setConsumerQueue(config.mqName);

		Result<Integer> result = messageService.directSendMessage(messageAddReqVo);
		log.info("直接发送消息响应:{}", JsonUtils.toJson(result));
	}
}
